package com.hxy.verificationCode.controller;


import cn.hutool.core.io.resource.ResourceUtil;

import com.hxy.verificationCode.config.PuzzleCaptcha;
import com.hxy.verificationCode.domain.CaptchaResult;
import com.hxy.verificationCode.domain.CaptchaVo;
import com.hxy.verificationCode.constant.CacheConstant;
import com.hxy.verificationCode.service.CaptchaService;
import com.hxy.common.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.util.Map;

/**
 * 验证码
 *
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private RedisCache redisCache;

    @GetMapping(value = "/")
    public CaptchaVo captcha() {
        PuzzleCaptcha puzzleCaptcha = new PuzzleCaptcha(ResourceUtil.getStream("images/captcha/default.jpg"));
        puzzleCaptcha.setImageQuality(Image.SCALE_AREA_AVERAGING);
        puzzleCaptcha.run();
        CaptchaVo captchaVo = captchaService.captcha(puzzleCaptcha);
        captchaVo.setCode(200);
        return  captchaVo;
    }

    @PostMapping(value = "/verify")
    public CaptchaResult verify(@RequestBody Map<String, Object> map) {
        CaptchaResult captchaResult = captchaService.verify(map);
        captchaResult.setCode(200);
        return captchaResult;
    }

    @PostMapping("/login")
    public void login(String username, String password, HttpServletRequest request) {
        CaptchaResult result = redisCache.getCacheObject(CacheConstant.CAPTCHA_RESULT + request.getRequestedSessionId());
        if (result == null || !result.isSuccess()) {
            throw new RuntimeException("验证失败");
        }
        redisCache.deleteObject(CacheConstant.CAPTCHA_RESULT + request.getRequestedSessionId());
        // 通过验证
    }
}
